package com.xnx3.kefu.site.controller;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xnx3.j2ee.util.SystemUtil;
import com.xnx3.BaseVO;
import com.xnx3.FileUtil;
import com.xnx3.StringUtil;
import com.xnx3.j2ee.controller.BaseController;
import com.xnx3.j2ee.service.SqlCacheService;
import com.xnx3.j2ee.service.impl.SqlCacheServiceImpl;
import com.xnx3.kefu.core.entity.Kefu;
import com.xnx3.kefu.core.entity.KefuJS;
import com.xnx3.kefu.core.entity.Zuoxi;
import com.xnx3.kefu.core.pluginManage.interfaces.manage.KefuJsPluginManage;
import com.xnx3.kefu.core.util.KefuPropertiesUtil;

/**
 * 生成可以放到第三方网站的js
 * @author 管雷鸣
 */
@Controller(value="KefuSiteJSController")
@RequestMapping("/")
public class SiteKefuController extends BaseController {
	@Resource
	private SqlCacheService sqlCacheService;

	/**
	 * 获取当前客服的 kefuJS 信息
	 * @author 管雷鸣
	 * @param id 坐席的id
	 * @param template 模板名，不穿默认是2，位于 resources/static/template/ 下的文件夹
	 */
	@ResponseBody
	@RequestMapping("siteKefu.js")
	public String getKefuJS(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "id", required = true) String id,
			@RequestParam(value = "template", required = false, defaultValue = "2") String template){
		response.setContentType("text/javascript;charset=UTF-8");
		
		if(id.length() < 1){
			return "console.log('kefu zuoxi is not find!');";
		}
		//读取坐席id对应的kefu
//		Kefu kefu = sqlCacheService.findAloneByProperty(Kefu.class, "userid", id);
		Zuoxi zuoxi = sqlCacheService.findById(Zuoxi.class, id);
		if(zuoxi == null){
			return "console.log('kefu zuoxi database on system cache, is not find!');";
		}
		
		Kefu kefu = sqlCacheService.findById(Kefu.class, zuoxi.getKefuid());
		if(kefu == null){
			return "console.log('kefu (in database) is not find!');";
		}
		
		//读取自定义js
		KefuJS kefuJS = sqlCacheService.findById(KefuJS.class, zuoxi.getKefuid());
		if(kefuJS == null){
			kefuJS = new KefuJS();
		}
//		String path = SystemUtil.getClassesPath()+"static/template/"+template+"/template.js";
//		String str = FileUtil.read(path);
		String siteKefuJs = null;
		try {
			siteKefuJs = StringUtil.inputStreamToString(SiteKefuController.class.getResourceAsStream("/META-INF/resources/template/"+template+"/template.js"), FileUtil.UTF8);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//获取一些参数
		String api = KefuPropertiesUtil.getProperty("kefu.api");
		if(api == null) {
			return "alert('please set kefu.properties - kefu.api');";
		}
		//容错，判断api是否末尾多加了/
		if(api.lastIndexOf("/") + 1 == api.length()) {
			//域名最后是以/结尾，那去掉最后的 /
			api = api.substring(0, api.length() -1);
		}
		
		/**** 针对html源码处理插件 ****/
		//jsFile
		List<String> pluginAppendJSFileList = KefuJsPluginManage.kefuJsAppendJsFile(request);
		if(pluginAppendJSFileList.size() > 0) {
			StringBuffer jsFileSB = new StringBuffer();
			for (int i = 0; i < pluginAppendJSFileList.size(); i++) {
				jsFileSB.append(" try{ kefu.util.synchronizesLoadJs('"+pluginAppendJSFileList.get(i)+"'); }catch(e){ console.log(e); } ");
			}
			siteKefuJs = siteKefuJs.replace("//{KefuJsInterface.kefuJsAppendJsFile}", jsFileSB.toString());
		}
		//jsCode
		String pluginAppendJSCode = KefuJsPluginManage.kefuJsAppendJsCode(request);
		if(pluginAppendJSCode != null && pluginAppendJSCode.length() > 0) {
			siteKefuJs = siteKefuJs.replace("//{KefuJsInterface.kefuJsAppendJsCode}", pluginAppendJSCode);
		}
		
		siteKefuJs = siteKefuJs.replaceAll("\\{host\\}", api)
			.replaceAll("\\{socketUrl\\}", KefuPropertiesUtil.getProperty("kefu.socket"))
			.replaceAll("\\{zuoxiid\\}", zuoxi.getId())
			.replaceAll("\\{color\\}", kefuJS.getColor())
			.replaceAll("\\{backgroundColor\\}", kefuJS.getBackgroundColor())
			.replaceAll("\\{autoHelloTime\\}", kefu.getAutoHelloTime()+"")
			.replaceAll("\\{autoHelloText\\}", kefu.getAutoHelloText())
			;
		
		response.setContentType("text/javascript;charset=UTF-8");
		return siteKefuJs;
	}
	
}
